<template>
  <div class="cesium-hoverInfo">
    <div class="content-info">
      <div class="info-left">
        <div class="base-info">
          <div class="image">
            <img class="image" :src="showData.imgUrl || defUrl">
          </div>

          <div class="base-title">{{ showData.deviceName }}</div>
          <div class="base-addr">{{ showData.monitorAddress }}</div>
        </div>
        <div class="base-desc">
          <div class="desc-item">
            <span class="item-label">所属区域: </span>
            <span class="item-value"> {{ showData.administrativeRegion }}</span>
          </div>
          <div class="desc-item">
            <span class="item-label">暴露面积: </span>
            <span class="item-value">{{ showData.area}}</span>
          </div>
          <div class="desc-item">
            <span class="item-label">暴露人口: </span>
            <span class="item-value">{{ showData.population }}</span>
          </div>
        </div>
      </div>

      <div class=info-right>
        <div class="noise-info"  v-if="showData.deviceTypeCode !== 'ZP'">
          <div class="current-noise" :style="{color: showData.colorCode}">
            <div class="value">
              <span class="label">实时：</span><span class="noise">{{ showData.leqRtd || 0.00 }}<span class="unit">(dB)</span></span>
            </div>
            <div class="label"></div>
          </div>
          <div class="current-rates">
            <div class="value">
              <span class="label">采集率：</span><span class="noise">{{ showData.rates || 0.00 }}<span class="unit">%</span></span>
            </div>
            <div class="label"></div>
          </div>
          <div class="max-noise">
            <div class="value">
              <span class="label">最大：</span><span class="noise">{{ showData.maxRtd || 0.00 }}<span class="unit">(dB)</span></span>
            </div>
            <div class="label"></div>
          </div>
          <div class="min-noise">
            <div class="value">
              <span class="label">最小：</span><span class="noise">{{ showData.minRtd || 0.00 }}<span class="unit">(dB)</span></span>
            </div>
            <div class="label"></div>
          </div>


        </div>
        <div class="right-item-info">
          <div class="title">超标统计</div>
          <div class="info">
            <div class="item"><span class="item-label">昼间超标次数：</span><span class="item-value">{{ iatDeviceCompliances?.dayExceedanceNumber || 0 }}</span></div>
            <div class="item"><span class="item-label">昼间时间段：</span><span class="item-value">{{ iatDeviceCompliances?.daytimePeriod || '--'}}</span></div>
            <div class="item"><span class="item-label">夜间超标次数：</span><span class="item-value">{{ iatDeviceCompliances?.nightExceedanceNumber || 0 }}</span></div>
            <div class="item"><span class="item-label">夜间时间段：</span><span class="item-value">{{ iatDeviceCompliances?.nightimePeriod || '--'}}</span></div>
          </div>
        </div>
        <div class="right-item-info">
          <div class="title">投诉统计</div>
          <div class="info">
            <div class="item"><span class="item-label">累计投诉总数：</span><span class="item-value">{{ iatDeviceComplainVo?.total || 0}}</span></div>
            <div class="item"><span class="item-label">未处理总数：</span><span class="item-value">{{ iatDeviceComplainVo?.noHandle || 0}}</span></div>
          </div>
        </div>
        <div class="right-item-info" v-if="isShowNoiseChart">
          <div class="title">噪声分类统计</div>
          <div class="chartsView">
            <div id="echartsRefId" ref="echartsRef"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import { onMounted, onUnmounted, ref, useAttrs, nextTick } from "vue"
import * as echarts from "echarts"
import { gatherNoiseData } from "@mars/api/data/index"

import defUrl from "@mars/assets/image/system/no_img.png"
const attrs = useAttrs()
const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  isWarning: {
    type: Boolean,
    default: false
  }
})

const showData = ref(props.data || {})
const echartsRef = ref(null)
const noiseChart = ref(null)
const showNoiseChart = ref(["PZ", "ZP"])
const isShowNoiseChart = ref(false)
const iatDeviceComplainVo = ref(null)
const iatDeviceCompliances = ref(null)
let resizeObserver
onMounted(async () => {
  showData.value = props.data
  isShowNoiseChart.value = !showNoiseChart.value.includes(showData.value.deviceTypeCode)
  iatDeviceComplainVo.value = showData.value.iatDeviceComplainVo
  iatDeviceCompliances.value = showData.value.iatDeviceCompliances


  /** 获取设备的最大噪音、最小噪音、采集效率 */
  await getGatherNoiseData()

  nextTick(() => {
    noiseTypeChart()
  })

})

const getGatherNoiseData = async () => {
  // 1. 参数校验
  if (!showData.value?.code) {
    console.error("设备编码不能为空")
    return
  }

  try {
    // 2. 请求参数准备
    const params = {
      deviceCode: showData.value.code,
      timestamp: Date.now() // 可选：添加时间戳防止缓存
    }

    // 3. 发起请求并处理响应
    const response = await gatherNoiseData(params)

    // 4. 响应数据校验
    if (!response?.data) {
      throw new Error("响应数据格式不正确")
    }

    const arrData = response.data
    if (arrData.length > 0) {
      showData.value.maxRtd = arrData[0].maxRtd
      showData.value.minRtd = arrData[0].minRtd
      showData.value.rates = arrData[0].ratio
    }

    // 5. 返回数据以便后续处理
    return arrData

  } catch (error) {
    // 6. 错误处理
    console.log("获取噪声数据失败:", error)

  }
}



onUnmounted(() => {
  if (noiseChart.value) {
    noiseChart.value.dispose()
  }
})


const noiseTypeChart = async () => {
  if (!echartsRef.value) { return }

  const voiceTypeList = showData.value.iatVoiceTypeVOList
  if (!voiceTypeList || voiceTypeList.length === 0) {
    console.warn("No data available for chart")
    return
  }


  const yAxisData = []
  const seriesData = []
  const countData = []
  // 计算噪声分类统计总数
  const totalcount = voiceTypeList.reduce((sum, item) => sum + Number(item.count), 0)

  // 准备数据
  voiceTypeList.forEach(item => {
    yAxisData.push(item.voiceTypeName)
    countData.push(item.count)
    seriesData.push(totalcount ? ((item.count / totalcount) * 100).toFixed(2) : 0)
  })

  // 初始化或更新图表
  // noiseChart.value.dispose()

  noiseChart.value = echarts.init(echartsRef.value)


  const option = {
      grid: {
        left: "75px",
        top: "5%",
        bottom: "5%",
        right: "130px"
      },
      xAxis: {
        type: "value",
        min: 0,
        max: 100,
        axisLabel: {
          color: "#cfffff",
          formatter: "{value}%"
        },
        show: false
      },
      yAxis: {
        type: "category",
        data: yAxisData,
        axisLabel: {
          fontSize: 11,
          color: "#cfffff"
        }
      },
      series: [
        {
          data: seriesData,
          type: "bar",
          label: {
            show: true,
            position: "right",
            color: "#fff",
            formatter: function (params) {
              const index = params.dataIndex
              return `${params.value}% (${countData[index]})`
            }
          },
          itemStyle: {
            color: "rgb(0,182,244)", // 设置柱子颜色
            barWidth: 10 // 设置柱子宽度
          }
        }
      ]
    }



    noiseChart.value.setOption(option)
    // noiseChart.value.resize()

    // 6. 添加响应式调整
    // const resizeHandler = () => noiseChart.value?.resize()
    // window.addEventListener("resize", resizeHandler)

    // // // 返回清理函数
    // return () => {
    //   window.removeEventListener("resize", resizeHandler)
    // }
}
</script>

<style lang="less" scoped>
.cesium-hoverInfo{
  position: absolute;
  z-index: 999;
  display: flex;
  padding: 15px;
  background: rgba(23, 49, 71, 0.8);
  width: 660px;
  height: 500px;
  gap: 20px;
  color: #cfffff;
}
.content-info {
  width:100%;
  height: 100%;
  overflow: hidden;
  display: flex;
}
.info-left {
  width: 220px;
  height: 100%;
  // margin-left: 15px;
  .base-info {
    width: 100%;
    .image{
      width: 180px;
      height: 180px;
      image{
        width: 100%;
        height: 100%;
      }
    }
    .base-title{
      margin-top: 10px;
      font-size: 20px;
      color: #00f3ff;
    }
    .base-addr{
      margin-top: 5px;
    }

  }
  .base-desc {
    margin-top: 20px;
    .desc-item{
      margin-bottom: 10px;
      .item-label{
        color: #00f3ff;
      }
      .item-value{

      }
    }
  }
  .company-info-echarts {
    width: 100%;
    height: 55%;
  }
}
.info-right {
  width: calc(100% - 200px);
  height: 100%;
  background: rgba(19, 72, 110, 0.11);
  .noise-info{
    margin-bottom: 10px;
    display: grid;
    grid-template-columns: 45% 55%; /* 2 columns */
    gap: 5px; /* spacing between items */
    .current-noise{

    }
    .label{
      font-size:20px;
    }
    .noise{
      font-size: 35px;
      font-weight: bold;
    }
    .unit{
      margin-left:10px;
      font-size: 16px;
    }
  }
  .right-item-info {
    width: 100%;
    margin-top: 15px;
    .title{
      width: 100%;
      height: 30px;
      line-height: 30px;
      color: #48c8ff;
      font-size: 20px;
      margin-bottom: 10px;
    }
    .info {
      display: grid;
      grid-template-columns: 40% 60%; /* 2 columns */
      gap: 10px; /* spacing between items */

      .item {
        display: flex;
        justify-content: left;
        // padding: 8px;
        // border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 20px;

      }
    }
    .chartsView {
      position: relative;
      width: 100%;
      height: 140px !important;  /* 强制高度 */
      min-height: 140px !important;

      #echartsRefId {
        position: absolute !important;
        left: 0;
        top: 0;
        width: 100% !important;
        height: 100% !important;
        min-height: 140px !important;

        }
      }
  }
}

// .image {
//   border: solid 2px #fff;
// }
</style>

